package com.reader.api.service.impl.usercenter;


import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.reader.api.constants.RedisKeyConstants;
import com.reader.api.entity.usercenter.APPToken;
import com.reader.api.mapper.usercenter.APPTokenMapper;
import com.reader.api.service.usercenter.IAPPTokenService;
import com.reader.core.redis.RedisDao;
import com.reader.core.utils.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.concurrent.TimeUnit;


/**
 * @@description  服务实现类
 * @author        jiahaikun
 * @date          2018-11-01
 */
@Service
@Transactional
public class APPTokenServiceImpl extends ServiceImpl<APPTokenMapper, APPToken> implements IAPPTokenService {

@Autowired
private RedisDao redisDao;

    @Override
    public APPToken createToken(int userId) {
        String accessToken=generateToken();
        String tokenKey=String.format(RedisKeyConstants.TOKEN,accessToken);
        Long expireDate = System.currentTimeMillis()+RedisKeyConstants.TOKEN_EXPIRES_TIME; //token 过期时间
        APPToken token=new APPToken();
        token.setUserID(userId);
        token.setAccess_token(accessToken);
        token.setExpire_in(expireDate);//token 过期时间
        redisDao.save(tokenKey,token,RedisKeyConstants.TOKEN_EXPIRES_TIME, TimeUnit.MILLISECONDS);
        return token;
    }

    @Override
    public APPToken getTokenInfoByToken(String token) {
        String tokenKey=String.format(RedisKeyConstants.TOKEN,token);
        return redisDao.getObject(tokenKey, APPToken.class);
    }

    @Override
    public void expireToken(String token) {
        String tokenKey=String.format(RedisKeyConstants.TOKEN,token);
        //设置立刻过期
        redisDao.setExpireTime(tokenKey,0, TimeUnit.MILLISECONDS);
    }


    /**
     * 生成token
     * @return
     */
    private String generateToken(){
        return IdUtils.generateUUID().replace("-", "");
    }
}